package com.hctforgreen.greenservice;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.MachineListEntity.MachineEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.ChildSerieEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.SerieEntity;
import com.hctforgreen.greenservice.ui.adapter.FuzzySearchBooksListAdapter;
import com.hctforgreen.greenservice.ui.widget.ChildSeriesListPopupView;
import com.hctforgreen.greenservice.ui.widget.SeriesListPopupView;
import com.hctforgreen.greenservice.utils.CheckDataVersionCodeUtil;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.KeyboardUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 技术资料页
 * 
 * @author Tallen Zhai
 * 
 */
public class TechnicalDataActivityV4 extends ParentActivity {
	/**
	 * 机组系列
	 */
	private SeriesListPopupView mSeriesListPopupView;
	/**
	 * 机型系列
	 */
	private ChildSeriesListPopupView mChildSeriesListPopupView;
	private SerieEntity mCurrentFirstEntity;
	private ChildSerieEntity mCurrentSecondEntity;

	private TechnicalDataActivityV4 mSelf;
	
	private LinearLayout loadLyt;
	private LinearLayout reloadLyt;
	private Button reloadBtn;
	private TextView loadTv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_techical_data_v4);
		initView();
		mSelf = this;
		/**
		 * 2016-12-31  390694 屏蔽直接判断资料包版本然后更新
		 * 增加判断用户去下载管理更新后的服务是否还在进行，若是进行则提示资料包正在更新，暂时无法使用
		 */
		//getAllBooksWithAllChildSeriesAndDbSerieName(false);
		isUpdateBooksServiceRunning();
		initSkinLayout();
		initTitleButtonBar();
		initWindow();
		initClickEdgehide();

		initDefaultCurrentEntity();
	}
	
	private void initView(){
		loadLyt = (LinearLayout) findViewById(R.id.lyt_default_load);
		reloadLyt = (LinearLayout) findViewById(R.id.lyt_default_reload);
		reloadBtn = (Button) findViewById(R.id.btn_default_reload);
		loadTv = (TextView) findViewById(R.id.tv_default_load);
	}
	protected void initDefaultCurrentEntity() {
		MachineEntity entity = (MachineEntity) getIntent()
				.getSerializableExtra(
						HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY);
		if (!entity.id.equals("")) {
			SerieEntity serieEntity = (SerieEntity) getIntent()
					.getSerializableExtra(
							HctConstants.ON_ACTIVITY_KEY_SERIES_ENTITY);
			ChildSerieEntity childSerieEntity = (ChildSerieEntity) getIntent()
					.getSerializableExtra(
							HctConstants.ON_ACTIVITY_KEY_CHILD_SERIE_ENTITY);

			final Button seriesBooksBtn = (Button) findViewById(R.id.btn_series);
			final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
			if (serieEntity != null) {
				mCurrentFirstEntity = serieEntity;
				seriesBooksBtn.setText(serieEntity.name);
			}
			if (childSerieEntity != null) {
				mCurrentSecondEntity = childSerieEntity;
				initFuzzySearchEt();
				setFocusable(true);
				childSeriesBooksBtn.setText(childSerieEntity.childSeriesName);
			}

		}
	}

	/**
	 * 点击边缘隐藏
	 */
	private void initClickEdgehide() {
		LinearLayout parentLyt = (LinearLayout) findViewById(R.id.lyt_parent);
		parentLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setTopLayoutVisible();
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
			}
		});
	}

	private boolean setTopLayoutVisible() {
		final LinearLayout topLyt = (LinearLayout) findViewById(R.id.lyt_top);
		if (topLyt.getVisibility() == View.GONE) {
			topLyt.setVisibility(View.VISIBLE);
			clearFocus();
			return true;
		}
		clearFocus();
		return false;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (setTopLayoutVisible()) {
				return true;
			}
			return super.onKeyDown(keyCode, event);
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.techical_data_title_hint));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				finish();
			}
		});
	}

	private void initWindow() {
		initSeriesListPopupView();
		initChildSeriesListPopupView();
		initSearchBtn();
	}

	private void initChildSeriesListPopupView() {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		seriesBooksBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				/**
				 * 2016-12-31 390694 增加判断更新资料的服务是否在进行，是  则提示
				 */
				boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(mSelf);
				if (isServiceRunning){
					Dialog dialog = null;
					AlertDialog.Builder builder = new AlertDialog.Builder(mSelf);
					builder.setTitle(R.string.dialog_default_title_hint)
							.setMessage(R.string.update_now)
							.setPositiveButton(R.string.dialog_confirm_hint,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog,
															int which) {
											dialog.dismiss();
										}
									});
					dialog = builder.create();
					dialog.show();
					return;
				}

				showListPopupView(v);
			}

			private void initListPopupView() {
				mChildSeriesListPopupView = new ChildSeriesListPopupView(
						TechnicalDataActivityV4.this, mCurrentFirstEntity,
						mCurrentSecondEntity, mSelf);

			}

			private void showListPopupView(View v) {
				initListPopupView();
				mChildSeriesListPopupView.showAsDropDown(v);
			}
		});
	}

	private void initSeriesListPopupView() {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_series);
		seriesBooksBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				/**
				 * 2016-12-31 390694 增加判断更新资料的服务是否在进行，是  则提示
				 */
				boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(mSelf);
				if (isServiceRunning){
					Dialog dialog = null;
					AlertDialog.Builder builder = new AlertDialog.Builder(mSelf);
					builder.setTitle(R.string.dialog_default_title_hint)
							.setMessage(R.string.update_now)
							.setPositiveButton(R.string.dialog_confirm_hint,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog,
															int which) {
											dialog.dismiss();
										}
									});
					dialog = builder.create();
					dialog.show();
					return;
				}

				showListPopupView(v);
			}

			private void initListPopupView() {
				if (mSeriesListPopupView == null) {
					mSeriesListPopupView = new SeriesListPopupView(
							TechnicalDataActivityV4.this, mCurrentFirstEntity,
							mCurrentSecondEntity, mSelf);
				}

			}

			private void showListPopupView(View v) {
				initListPopupView();

				mSeriesListPopupView.showAsDropDown(v);

			}
		});
	}

	public void initSerieEntity(SerieEntity currentFirstEntity) {
		mCurrentFirstEntity = currentFirstEntity;
	}

	public void initSeriesBtn(SerieEntity currentFirstEntity) {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_series);
		seriesBooksBtn.setText(currentFirstEntity.name);
	}

	public void initChildSerieEntity(ChildSerieEntity currentSecondEntity) {
		mCurrentSecondEntity = currentSecondEntity;
	}

	public void initChildSeriesBtn(ChildSerieEntity currentSecondEntity) {
		final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		childSeriesBooksBtn.setText(currentSecondEntity.childSeriesName);

	}

	public void setFocusable(boolean bCanFocus) {
		// final EditText inputEt = (EditText) findViewById(R.id.et_input);
		// inputEt.setFocusable(bCanFocus);
		// inputEt.setFocusableInTouchMode(bCanFocus);
	}

	public void clearChildSeriesBtn() {
		final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		childSeriesBooksBtn.setText("");

	}

	public void initBooksList() {
		initFuzzySearchEt();
	}

	private void initFuzzySearchEt() {

		final LinearLayout topLyt = (LinearLayout) findViewById(R.id.lyt_top);
		final EditText inputEt = (EditText) findViewById(R.id.et_input);
		inputEt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// if (!hasFocus) {
				// topLyt.setVisibility(View.VISIBLE);
				// } else if (hasFocus) {
				// if(!canDoFuzzySearch()){
				//
				// return;
				// }
				// topLyt.setVisibility(View.GONE);
				//
				// }

			}

			private boolean canDoFuzzySearch() {
				final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
				if (!childSeriesBooksBtn.getText().equals("")) {
					return true;
				} else {
					return false;
				}
			}
		});

	}
	 /**
	  * 点击搜索
	  */
	private void initSearchBtn() {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_series);
		final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		final EditText inputEt = (EditText) findViewById(R.id.et_input);
		final Button searchBtn = (Button) findViewById(R.id.btn_search);
		searchBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/**
				 * 2016-12-31 390694 增加判断更新资料的服务是否在进行，是  则提示
				 */
				boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(mSelf);
				if (isServiceRunning){
					Dialog dialog = null;
					AlertDialog.Builder builder = new AlertDialog.Builder(mSelf);
					builder.setTitle(R.string.dialog_default_title_hint)
							.setMessage(R.string.update_now)
							.setPositiveButton(R.string.dialog_confirm_hint,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog,
															int which) {
											dialog.dismiss();
										}
									});
					dialog = builder.create();
					dialog.show();
					return;
				}

				if (seriesBooksBtn.getText().toString().equals("")) {
					Toast.makeText(TechnicalDataActivityV4.this,
							R.string.techical_data_two_hint, Toast.LENGTH_SHORT)
							.show();
					return;
				}
				if (childSeriesBooksBtn.getText().toString().equals("")) {
					Toast.makeText(TechnicalDataActivityV4.this,
							R.string.techical_data_three_hint,
							Toast.LENGTH_SHORT).show();
					return;
				}
				setTopLayoutVisible();
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				getDbBooksUseChildSeriesId(mCurrentFirstEntity,
						mCurrentSecondEntity, inputEt.getText().toString()
								.trim());
			}
		});
	}

	/*
	 * private void fuzzySearchBookList(ChildSerieEntity currentSecondEntity,
	 * final String keyWord) { final View fuzzySearchLyt =
	 * findViewById(R.id.lyt_fuzzy_search); final LinearLayout emptyLyt =
	 * (LinearLayout) findViewById(R.id.lyt_default_list_empty);
	 * 
	 * fuzzySearchLyt.setVisibility(View.VISIBLE); if(keyWord.equals("")){
	 * if(currentSecondEntity != null && currentSecondEntity.dataList != null &&
	 * currentSecondEntity.dataList.size() > 0){
	 * emptyLyt.setVisibility(View.GONE);
	 * 
	 * initFuzzySearchLv(fuzzySearchLyt, currentSecondEntity.dataList); }else
	 * if(currentSecondEntity == null || currentSecondEntity.dataList == null ||
	 * currentSecondEntity.dataList.size() == 0){ //
	 * fuzzySearchLyt.setVisibility(View.GONE);
	 * emptyLyt.setVisibility(View.VISIBLE); }
	 * 
	 * }else if(!keyWord.equals("")){
	 * 
	 * List<BookEntity> bookList = null; for(BookEntity bean :
	 * currentSecondEntity.dataList){
	 * 
	 * if(bean.displayName.contains(keyWord)){
	 * 
	 * if(bookList == null){ bookList = new ArrayList<BookEntity>(); }
	 * bookList.add(bean); }
	 * 
	 * } if(bookList != null && bookList.size() > 0){
	 * emptyLyt.setVisibility(View.GONE); initFuzzySearchLv(fuzzySearchLyt,
	 * bookList); }else if(bookList == null || bookList.size() == 0){ //
	 * fuzzySearchLyt.setVisibility(View.GONE);
	 * emptyLyt.setVisibility(View.VISIBLE); }
	 * 
	 * }
	 * 
	 * }
	 */
	private void initFuzzySearchLv(final View fuzzySearchLyt,
			ListView fuzzySearchLV, final List<BookEntity> dataList) {

		new FuzzySearchBooksListAdapter(TechnicalDataActivityV4.this,
				fuzzySearchLV, dataList);

		fuzzySearchLV.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				final BookEntity entity = (BookEntity) dataList.get(position);
				EntryCatalogUtil catalogUtil = new EntryCatalogUtil();
				try {
					if (catalogUtil.startEntryCatalogActivity(
							TechnicalDataActivityV4.this, entity, true)) {
						setTopLayoutVisible();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
	}

	private void clearFocus() {

		/**
		 * 使用EditText左侧的ImageView抢Focus
		 */
		View requestFocusTv = (View) findViewById(R.id.iv_request_focus);
		requestFocusTv.requestFocus();

		final EditText searchInputEt = (EditText) findViewById(R.id.et_input);
		searchInputEt.clearFocus();
	}
/**
 * 点击搜素时根据子系列ID查找书
 * @param currentFirstEntity
 * @param currentSecondEntity
 * @param keyWord
 */
	private void getDbBooksUseChildSeriesId(
			final SerieEntity currentFirstEntity,
			final ChildSerieEntity currentSecondEntity, final String keyWord) {
		final View convertView = findViewById(R.id.lyt_parent);
		final ListView listView = (ListView) convertView
				.findViewById(R.id.lst_default_list);
		final LinearLayout loadLyt = (LinearLayout) convertView
				.findViewById(R.id.lyt_default_list_load);
		final LinearLayout reloadLyt = (LinearLayout) convertView
				.findViewById(R.id.lyt_default_list_reload);
		final Button reloadBtn = (Button) convertView
				.findViewById(R.id.btn_default_list_reload);

		final View fuzzySearchLyt = findViewById(R.id.lyt_fuzzy_search);
		final LinearLayout emptyLyt = (LinearLayout) findViewById(R.id.lyt_default_list_empty);
		listView.setDivider(getResources().getDrawable(R.drawable.ic_driver));

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);

					hctResult = (HctResult) msg.obj;

					List<BookEntity> dataList = getSearchTechDataBookLst(
							hctResult, keyWord);
					if (dataList == null || dataList.size() == 0) {
						listView.setVisibility(View.GONE);
						emptyLyt.setVisibility(View.VISIBLE);
						return;
					}
					listView.setVisibility(View.VISIBLE);
					emptyLyt.setVisibility(View.GONE);
					initFuzzySearchLv(fuzzySearchLyt, listView, dataList);
					break;

				case HctConstants.STATUS_FAILD:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.VISIBLE);
					listView.setVisibility(View.GONE);
					emptyLyt.setVisibility(View.GONE);
					reloadBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							getDbBooksUseChildSeriesId(currentFirstEntity,
									currentSecondEntity, keyWord);
						}
					});
					break;
				}
			}

			private List<BookEntity> getSearchTechDataBookLst(
					HctResult hctResult, String keyWord) {
				List<BookEntity> dataList = (List<BookEntity>) hctResult.data;
				if(dataList!=null){
					List<BookEntity> tmpList = new ArrayList<BookEntity>();
					for (BookEntity bEntity : dataList) {
						if (!bEntity.booktypeId.equals("001")
								|| !bEntity.displayName.contains(keyWord)) {
							tmpList.add(bEntity);
						}
					}

					dataList.removeAll(tmpList);
				}else{
					dataList=new ArrayList<BookEntity>();
				}
				
				return dataList;
			}

		};

		fuzzySearchLyt.setVisibility(View.VISIBLE);
		loadLyt.setVisibility(View.VISIBLE);
		reloadLyt.setVisibility(View.GONE);
		listView.setVisibility(View.GONE);
		emptyLyt.setVisibility(View.GONE);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(
							TechnicalDataActivityV4.this);

					HctResult result = controller.getDbBooksUseChildSeriesId(
							currentFirstEntity.id,
							currentSecondEntity.childSeriesId);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}
	
	/**
	 * 获取资料下面的子系列
	 * 
	 * 390694---20160325添加
	 */
		private void getAllBooksWithAllChildSeriesAndDbSerieName(final boolean bTopRefresh) {

			final Handler handler = new Handler() {
				public void handleMessage(Message msg) {

					HctResult hctResult = new HctResult();
					switch (msg.what) {
					case HctConstants.STATUS_SUCCESS:
						//Log.i("hh", "加载成功");
						loadLyt.setVisibility(View.GONE);
						reloadLyt.setVisibility(View.GONE);
						//Log.i("hh", "隐藏进度条");
						break;

					case HctConstants.STATUS_FAILD:
						//Log.i("hh", "加载失败");
						loadLyt.setVisibility(View.GONE);
						reloadLyt.setVisibility(View.VISIBLE);
						reloadBtn.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								getAllBooksWithAllChildSeriesAndDbSerieName(bTopRefresh);
							}
						});
						break;
					}
				}

			};
			loadTv.setVisibility(View.VISIBLE);
			loadLyt.setVisibility(View.VISIBLE);
			reloadLyt.setVisibility(View.GONE);
			new Thread() {
				public void run() {
					Message message = new Message();
					try {
						HctController controller = new HctController(mSelf);

						HctResult result = controller
								.getAllBooksWithAllChildSeries2Db(bTopRefresh, 0);
						if (result.status == HctConstants.STATUS_SUCCESS) {
							message.what = result.status;
							message.obj = result;
						} else {
							message.what = HctConstants.STATUS_FAILD;
						}
					} catch (Exception e) {
						e.printStackTrace();

					}
					handler.sendMessage(message);
				}
			}.start();
		}

	/**
	 * 2016-12-31
	 * 390694 增加判断更新资料的服务是否正在更新，
	 * 更新：提示正在更新资料包，不能查询阅读;
	 * 不更新：若数据库已更新且资料包版本不是最新，则可以查询阅读；
	 * ****  若资料包版本不是最新，则提示去下载管理更新
	 */
	public void isUpdateBooksServiceRunning(){
		boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(mSelf);
		CheckDataVersionCodeUtil checkDataVersionCodeUtil = new CheckDataVersionCodeUtil();
		if (isServiceRunning){
			Dialog dialog = null;
			AlertDialog.Builder builder = new AlertDialog.Builder(mSelf);
			builder.setTitle(R.string.dialog_default_title_hint)
					.setMessage(R.string.update_now)
					.setPositiveButton(R.string.dialog_confirm_hint,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
													int which) {
									dialog.dismiss();
								}
							});
			dialog = builder.create();
			dialog.show();
		}else{
			checkDataVersionCodeUtil.new CheckDataVersionCodeTask(R.string.debug_activity_update_data_content,
					R.string.terminal_update_data_title_2, mSelf, true,
					null, null, null, null, null).execute(mSelf);

		}

	}
}
